# 创建时间：2025/5/2 星期五 20:48
# 创建人：李德才


"""
with语句遵循了Python的上下文管理协议，即with语句会自动调用对象的__enter__()和__exit__()方法
在with语句中，文件对象会自动调用__enter__()方法，该方法会返回文件对象本身。
在with语句块结束时，文件对象会自动调用__exit__()方法，该方法会关闭文件。
"""
with open("桌面.jpg", "rb") as file:
    with open("桌面2.jpg", "wb") as file2:
        file2.write(file.read())


class MyFile:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()


with MyFile("桌面.jpg", "rb") as file:
    with MyFile("桌面3.jpg", "wb") as file2:
        file2.write(file.read())
